package com.platform.task.job;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

/**
 * 
 * 通过spring初始化bean方式执行任务启动，在实现方法afterPropertiesSet中做定时任务处理
 */
@Service
public class DeviceFaultManagerTask implements InitializingBean {

	private static Logger log = Logger.getLogger(DeviceFaultManagerTask.class);

	public static long INITIAL_DELAY = 10000;// 初试延时执行时间

	// @Value("${device_fault_insert_flag}")
	protected String device_fault_insert_flag = "ON";

	// 定时任务执行周期加载配置文件的字段
	// @Value("${device_fault_insert_period}")
	protected String periodString = "60";

	// 初始化定时任务的周期
	private static long period = 60 * 60 * 1000l;

	/**
	 * 开启定时任务
	 */
	public void afterPropertiesSet() throws Exception {
		// TODO 判断定时是否启动
		if ("ON".equals(device_fault_insert_flag)) {
			log.info("task is start............");
			// 判断配置文件中是否配置了定时任务的周期
			if (StringUtils.isNotEmpty(periodString)) {
				period = Long.parseLong(periodString);
			}
			// 启动定时任务
			schedulTask();
		}
	}

	/**
	 * 开启定时任务。
	 */
	public void schedulTask() {
		ScheduledExecutorService executors = Executors.newSingleThreadScheduledExecutor();
		executors.scheduleAtFixedRate(new DeviceFaultManagerTaskJob(), INITIAL_DELAY, period, TimeUnit.MILLISECONDS);
	}

	private class DeviceFaultManagerTaskJob implements Runnable {

		public void run() {
			try {
				log.info("task is start............");
				// 业务处理

				log.info("task is end............");
			} catch (Exception e) {
				log.error("task has exception", e);
			}
		}

	}
}
